package com.enation.app.javashop.manager.api.shop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.enation.app.javashop.core.goods.model.dos.TagsDO;
import com.enation.app.javashop.core.member.model.vo.ShopTagsVO;
import com.enation.app.javashop.framework.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 商铺标签控制器
 * @author 孙建
 */
@RestController
@RequestMapping("/admin/shops/tags")
@Api(description = "商铺标签相关API")
public class ShopTagsController {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	private static List<ShopTagsVO> cacheList = new ArrayList<>();
	static {
		cacheList.add(new ShopTagsVO("超市", "MKT"));
		cacheList.add(new ShopTagsVO("果蔬", "FAVEG"));
		cacheList.add(new ShopTagsVO("生鲜", "FRESH"));
		cacheList.add(new ShopTagsVO("食品饮料", "FABVG"));
		cacheList.add(new ShopTagsVO("健身娱乐", "ENT"));
		cacheList.add(new ShopTagsVO("药品买卖", "BDS"));
		cacheList.add(new ShopTagsVO("饭店外卖", "HOTEL"));
		cacheList.add(new ShopTagsVO("电器类", "ELEAPP"));
	}

	private static final String SHOP_TAGS_KEY = "SHOP_TAGS";


	@ApiOperation(value	= "查询商品标签列表", response = TagsDO.class)
	@GetMapping
	public List<ShopTagsVO> list()	{
		String shopTagsJson = stringRedisTemplate.opsForValue().get(SHOP_TAGS_KEY);
		if(StringUtil.isEmpty(shopTagsJson)){
			shopTagsJson = JSON.toJSON(cacheList).toString();
			stringRedisTemplate.opsForValue().set(SHOP_TAGS_KEY, shopTagsJson);
			return cacheList;
		}else{
			return JSONArray.parseArray(shopTagsJson, ShopTagsVO.class);
		}
	}

	@ApiOperation(value	= "添加店铺标签")
	@PostMapping
	public List<ShopTagsVO> addShopTag(@RequestBody ShopTagsVO shopTagsVO)	{
		// 查询缓存中店铺标签
		String shopTagsJson = stringRedisTemplate.opsForValue().get(SHOP_TAGS_KEY);
		List<ShopTagsVO> shopTagsVOS = JSONArray.parseArray(shopTagsJson, ShopTagsVO.class);
		shopTagsVOS.add(shopTagsVO);

		// 更新缓存
		stringRedisTemplate.opsForValue().set(SHOP_TAGS_KEY,  JSON.toJSON(shopTagsVOS).toString());
		return shopTagsVOS;
	}

}
